#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# Reason-GPL: import-scapy
import sys
from scapy.all import sniff, IP, ICMP, TCP

def handle_pkt(pkt):
    """处理接收到的包"""
    if IP in pkt:
        src_ip = pkt[IP].src
        dst_ip = pkt[IP].dst
        proto = pkt[IP].proto

        # 打印ICMP包（ping）
        if ICMP in pkt:
            print(f"Received ICMP packet: {src_ip} -> {dst_ip}")
            pkt.show2()
        
        # 打印TCP包（可选）
        elif TCP in pkt and pkt[TCP].dport == 1234:
            print(f"Received TCP packet: {src_ip}:{pkt[TCP].sport} -> {dst_ip}:1234")
            print(f"Payload: {bytes(pkt[TCP].payload).decode('utf-8')}")

        sys.stdout.flush()

def main():
    iface = sys.argv[1] if len(sys.argv) > 1 else "eth0"
    print(f"Sniffing on interface {iface}...")
    sniff(iface=iface, prn=lambda x: handle_pkt(x))

if __name__ == '__main__':
    main()